package com.distribute.application.api.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.stream.FileImageOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.distribute.framework.core.web.helper.Utils;


public class WxMiniQrCodeUtil {
	static String upload_forder = Utils.config("upload.forder");//上传图片保存的路径
	static String upload_domain = Utils.config("upload.domain");//图片服务的域名地址	
	private static final Logger log = LoggerFactory
			.getLogger(WxMiniQrCodeUtil.class);

	/**
	 * 通过该接口生成的小程序码，永久有效，数量暂无限制。用户扫描该码进入小程序后，开发者需在对应页面获取的码中 scene 字段的值，
	 * 再做处理逻辑。使用如下代码可以获取到二维码中的 scene 字段的值。调试阶段可以使用开发工具的条件编译自定义参数 scene=xxxx
	 * 进行模拟，开发工具模拟时的 scene 的参数值需要进行 urlencode。同时需要注意，此接口的page参数中不能带任何参数，
	 * 参数都在scene 参数中处理，切记！！！
	 * 
	 * @param sceneStr
	 *            最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&’()*+,/:;=?@-._~，其它字符请自行
	 *            编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
	 * @param accessToken
	 * @return
	 */
	public static String getMiniCode(String sceneStr, String accessToken,String paths,String fileName) {
		RestTemplate rest = new RestTemplate();
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
					+ accessToken;
			Map<String, Object> param = new HashMap<String, Object>();
			//param.put("scene", "doctorId=57");
			param.put("scene", sceneStr);
			//param.put("page", "sdh/register/register");
			param.put("page", paths);		
			param.put("width", 430);
			param.put("auto_color", false);
			Map<String, Object> line_color = new HashMap<String, Object>();
			line_color.put("r", 0);
			line_color.put("g", 0);
			line_color.put("b", 0);
			param.put("line_color", line_color);
			String json = JSONObject.toJSONString(param);
			log.info("调用生成微信URL接口传参:" + json);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
			HttpEntity requestEntity = new HttpEntity(json, headers);
			ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST,
					requestEntity, byte[].class, new Object[0]);
			log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody().toString());
			byte[] result = entity.getBody();
			String sApp="qrcode";//上传应用
			String filePah=sApp+"/";
			new File(upload_forder+filePah).mkdirs();
			byte2image(result,upload_forder+filePah+fileName);
//			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
//					+ accessToken;
//			
//			CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
//            HttpPost httpPost = new HttpPost(url);
//            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
//            String body = JSON.toJSONString(param);
//            StringEntity entity;
//            entity = new StringEntity(body);
//            entity.setContentType("image/png");
//
//            httpPost.setEntity(entity);
//            HttpResponse response;
//
//            response = httpClient.execute(httpPost);
//            InputStream inputStream = response.getEntity().getContent();
//            
//				String sApp="attached/qrcode";//上传应用
//				String filePah=sApp+"/";
//				String fileName=new SimpleDateFormat("HHmmssS"+Utils.rand(999)).format(new Date())+".png";
//				new File(upload_forder+filePah).mkdirs();
//			FileOutputStream out = new FileOutputStream(upload_forder+filePah+fileName);
//
//            byte[] buffer = new byte[8192];
//            int bytesRead = 0;
//            while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
//                out.write(buffer, 0, bytesRead);
//            }
//            out.flush();
//            out.close();
			// String imgName = OSSUtils.uploadFileToOSS(result, "png");
		
			 return upload_domain+filePah+fileName;
		} catch (Exception e) {
			log.error("调用小程序生成微信永久小程序码URL接口异常", e);
		}
		return null;
	}
	public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals(""))
            return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        }
        catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
    /* @param instreams 二进制流
* @param imgPath 图片的保存路径
* @param imgName 图片的名称
* @return
*      1：保存正常
*      0：保存失败
*/
public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){

   int stateInt = 1;
   if(instreams != null){
       try {
           File file=new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等
           FileOutputStream fos=new FileOutputStream(file);
                
           byte[] b = new byte[1024];
           int nRead = 0;
           while ((nRead = instreams.read(b)) != -1) {
               fos.write(b, 0, nRead);
           }
           fos.flush();
           fos.close();                
       } catch (Exception e) {
           stateInt = 0;
           e.printStackTrace();
       } finally {
           try {
            instreams.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       }
   }
   return stateInt;
}
/**
 * 字符串转二进制
 * @param str 要转换的字符串
 * @return  转换后的二进制数组
 */
public static byte[] hex2byte(String str) { // 字符串转二进制
    if (str == null)
        return null;
    str = str.trim();
    int len = str.length();
    if (len == 0 || len % 2 == 1)
        return null;
    byte[] b = new byte[len / 2];
    try {
        for (int i = 0; i < str.length(); i += 2) {
            b[i / 2] = (byte) Integer
                    .decode("0X" + str.substring(i, i + 2)).intValue();
        }
        return b;
    } catch (Exception e) {
        return null;
    }
}
}

